import 'package:book_manager_app/utils/common/user/account.dart';
import 'package:book_manager_app/utils/common/user/user_info.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:http_manager/http_manager.dart';
import 'package:encrypt/encrypt.dart';
import 'package:pointycastle/asymmetric/api.dart';
import '../../../../utils/common/user/account_manager.dart';
import '../../../routes/app_pages.dart';
import '../../../utils/common/app_manager.dart';
import '../../../utils/common/base_controller.dart';
import '../../../utils/widget/common.dart';
import '../../../utils/common/result_code.dart';
import '../request/user_request.dart';

  // PEM格式公钥
  final publicKeyPEM = '''-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM51dgYtMyF+tTQt80sfFOpSV27a7t9u
aUVeFrdGiVxscuizE7H8SMntYqfn9lp8a5GH5P1/GGehVjUD2gF/4kcCAwEAAQ==
-----END PUBLIC KEY-----''';

class LoginController extends BaseController {
  // 账号
  final TextEditingController accountVC = TextEditingController();
  // 密码
  final TextEditingController passwordVC = TextEditingController();
  // 验证码
  final TextEditingController shortCodeVC = TextEditingController();
  final TextEditingController hostVC = TextEditingController();

  // late TextField accountTextField;
  // late TextField passwordTextField;
  // late TextField shortCodeTextField;

  //可以获取验证码
  final canLogin = false.obs;
  final checkboxSelected = false.obs;
  
  // 验证码图片数据
  final captchaImage = Rx<String?>(null);
  // 验证码uuid
  String? captchaUuid;
  // 验证码是否已加载
  final isCaptchaLoaded = false.obs;

  String account = "";
  List<String> loginHistory = [];

  @override
  void onInit() {
    super.onInit();

  }

  @override
  void onReady() {
    super.onReady();
    _loadLastAccount();
    getCaptchaImage();
  }

    // 填充账号对应的密码
  Future<String> _fillPasswordForAccount(String account) async {
    return await AccountManager.getPasswordForAccount(account)??"";
  }

  // 添加自动填充上次登录信息的方法
  void _loadLastAccount() async {
    final lastAccount = AccountManager.getLoginHistory();
    if (lastAccount.isNotEmpty) {
      accountVC.text = lastAccount.first.keys.first;
      final password = await _fillPasswordForAccount(lastAccount.first.keys.first);
      if (password.isNotEmpty) {
        passwordVC.text = password;
      }
      account = lastAccount.first.keys.first;
      loginHistory = lastAccount.map((e) => e.keys.first).toList();
    }
  }

  getCaptchaImage() {
    UserRequest.getCaptchaImage(AppManager.uuid).then((result) {
      if (result.success) {
        // 从返回结果解析验证码图片和uuid
        final String dataUrl = result.data["img"];
        // 提取纯base64内容，去掉"data:image/png;base64,"前缀
        if (dataUrl.contains("base64,")) {
          captchaImage.value = dataUrl.split("base64,")[1];
        } else {
          captchaImage.value = dataUrl;
        }
        captchaUuid = result.data["uuid"];
        isCaptchaLoaded.value = true;
      } else {
        showMessage("获取验证码失败，请重试");
        isCaptchaLoaded.value = false;
      }
    });
  }

  // 刷新验证码
  refreshCaptcha() {
    captchaImage.value = null;
    isCaptchaLoaded.value = false;
    getCaptchaImage();
  }

  loginClick() async {
    closeKeyboard();
    if (accountVC.text == "") {
      showMessage("请输入账号或手机号");
      return;
    }
    if (passwordVC.text == "") {
      showMessage("请输入密码");
      return;
    }
    if (shortCodeVC.text == "") {
      showMessage("请输入验证码");
      return;
    }
    // if(!checkboxSelected){
    //   showMessage("请先阅读与同意《服务协议》和《隐私协议》");
    //   return;
    // }
    
    // 对密码进行RSA加密
    final encryptedPassword = encryptPasswordSync(passwordVC.text, publicKeyPEM);
    gotoLoginWithPassword(accountVC.text, encryptedPassword, shortCodeVC.text);
  }

  // 同步方法实现（使用encrypt库）
  String encryptPasswordSync(String password, String publicKey) {
    try {
      // 解析PEM格式公钥
      final parser = RSAKeyParser();
      final RSAPublicKey rsaPublicKey = parser.parse(publicKey) as RSAPublicKey;
      
      // 创建加密器
      final encrypter = Encrypter(RSA(publicKey: rsaPublicKey));
      
      // 加密数据
      final encrypted = encrypter.encrypt(password);
      
      // 返回Base64编码结果
      return encrypted.base64;
    } catch (e) {
      print('加密失败: $e');
      return '';
    }
  }

  // 密码登录
  gotoLoginWithPassword(String account, String password, [String? captcha]) {
    if (ObjectUtil.isEmpty(AppManager.userToken)) {
      _loginWitPassword(account, password, captcha);
    }else {
      debugPrint("AppManager.userToken = null");
      debugPrint("正在获取 UserToken...");
      showLoadingMessage("正在获取token...");
      UserRequest.getUserToken(AppManager.uuid).then((result) {
        if (result.success && AppManager.userToken.isNotEmpty) {
          _loginWitPassword(account, password, captcha);
        }else {
          dismissLoading();
          _loginWitPassword(account, password, captcha);
        }
      });
    }
  }


  _loginWitPassword(String account, String password, [String? captcha]) async {
    showLoadingMessage("拼命登录中...");
    // 修复登录请求参数
    final Map<String, dynamic> loginParams = {
      "account": account,
      "password": password,
    };
    
    // 如果有验证码信息，添加到请求参数中
    if (captcha != null && captcha.isNotEmpty && captchaUuid != null) {
      loginParams["captcha"] = captcha;
      loginParams["uuid"] = captchaUuid;
    }
    
    UserRequest.loginWithPassword(
      account: account, 
      password: password,
      code: captcha,
      uuid: captchaUuid
    ).then((result) {
      dismissLoading();
      if (result.success) {
        AppManager.isLogin = true;
        Get.offAndToNamed(Routes.HOME);
        AppManager.userToken = result.data["token"];
        
        
        AccountManager.addAccountToHistory(account, passwordVC.text);
        // 获取用户信息
        UserRequest.getUserInfo().then((result) {
          if (result.success) {
            AppManager.userInfo = UserModel.fromJson(result.data);
            AppManager.storeId = AppManager.userInfo?.stores.first.storeId ?? 0;
            HttpManager.setHeaders({"StoreId": AppManager.storeId});
            HttpManager.setHeaders({"Authorization": "Bearer ${AppManager.userToken}"});
          }
        });
      }else if (result.code == "10102") {
        gotoLoginWithPassword(account, password, captcha);
      }else {
        // 登录失败时刷新验证码
        refreshCaptcha();
      }
    });
  }

  checkboxClick(bool? value) {
    closeKeyboard();
    checkboxSelected.value = value!;
    canLogin.value = (
        accountVC.text.isNotEmpty
            && passwordVC.text.length >= 6
            && shortCodeVC.text.isNotEmpty
            && checkboxSelected.value == true)
        ? true
        : false;
  }

}